var boardUrl = "";
var fontResizeTarget = "mflick2";

var popupOpenYN = false;

var VIEW_DETAIL = "01";
var VIEW_LAYER = "02";
var VIEW_MAP = "03";

hoverClassRegEx = new RegExp('(^|\\s)iScrollHover(\\s|$)'),
		removeClass = function() {
			if (this.hoverTarget) {
				clearTimeout(this.hoverTimeout);
				this.hoverTarget.className = this.hoverTarget.className
						.replace(hoverClassRegEx, '');
				this.target = null;
			}
		};

function hideAddressBar() {
	if (getDeviceOS() == "android") {
		if (document.documentElement.scrollHeight < window.outerHeight
				/ window.devicePixelRatio)
			document.documentElement.style.height = (window.outerHeight / window.devicePixelRatio)
					+ 'px';
		setTimeout(window.scrollTo(0, 1), 300);
	} else {
		setTimeout(window.scrollTo(0, 1), 300);
	}
}

function getDeviceOS() {
	var uAgent = navigator.userAgent.toLowerCase();
	console.log("##############################=" + uAgent);
	if (window.navigator.userAgent.indexOf("Trident") > 0) {
		return "Trident";
	} else if (uAgent.indexOf("android") != -1) {
		if (uAgent.indexOf("shv-e140s") != -1
				|| uAgent.indexOf("shw-m380s") != -1
				|| uAgent.indexOf("shw-m480w") != -1) {
			return "tab";
		} else {
			return "android";
		}
	} else if (uAgent.indexOf("iphone") != -1 || uAgent.indexOf("ipod") != -1) {
		return "iphone";
	} else if (uAgent.indexOf("4_3_5") != -1) {
		return "4_3_5";
	} else if (uAgent.indexOf("ipad") != -1) {
		return "ipad";
	} else if (uAgent.indexOf("windows phone") != -1) {
		return "windows";
	} else if (uAgent.indexOf("bada") != -1) {
		return "bada";
	} else if (uAgent.indexOf("blackberry") != -1 || uAgent.indexOf("bb") != -1) {
		return "blackberry";
	} else if (uAgent.indexOf("mac") != -1) {
		return "macpc";
	} else if (uAgent.indexOf("windows nt") != -1) {
		return "winpc";
	} else {
		return "";
	}
}

var targets = new Array('list > li > a', 'sbj', 'cnt_infoArea',
		'cnt_infoArea > table > tr > td', 'contRel > li > dl > dd',
		'conTitle_IH01', 'contents_IH02', 'X_ARTICLE', 'pbtit', 'cont');
// Specify spectrum of different font sizes:
var LIMIT_FONT_CHG = 2;
var currentFontChg = 1;

// ##글씨크게/작게------------------------------------------------------------
// Specify affected tags. Add or remove from list:
function ts(inc) {
	var fontSize = $("#fontChangeForm input[name='fontSize']").val();

	switch (fontSize) {
	case "Big":
		currentFontChg = 2;
		break;
	case "Small":
		currentFontChg = 0;
		break;

	}
	var changeFontChg = currentFontChg;
	if (inc > 0) {
		changeFontChg += inc;
		if (changeFontChg > LIMIT_FONT_CHG) {
			return;
		}
	} else {
		changeFontChg += inc;
		if (changeFontChg < -1) {
			return;
		}
	}
	fontSize = "";
	if (changeFontChg != 1) {
		if (changeFontChg > currentFontChg) {
			fontSize = "Big";
		} else {
			fontSize = "Small";
		}
	}

	currentFontChg = changeFontChg;
	$("#fontChangeForm input[name='fontSize']").val(fontSize);
	$('#fontChangeForm').submit();

}
// ##글씨크게/작게------------------------------------------------------------

/**
 * 작업중 메세지
 */
function showAlertWorking() {
	alert("작업중입니다.");
}

var main_submenu01_scroll;
var searchType;
var searchId;
/**
 * 디렉토리 상단 메뉴 슬라이더 생성
 */
function fncInitTopMenuSlider() {
	if (document.getElementById("main_submenu01")) {
		main_submenu01_scroll = new iScroll('main_submenu01', {
			snap : 'li',
			hScrollbar : false,
			vScroll : false,
			momentum : false,
			onScrollStart : function() {
				// trans_arrow_show();
			},
			onBeforeScrollStart : function(e) {

				if (this.absDistX > (this.absDistY + 10)) {
					// user is scrolling the x axis, so prevent the browsers'
					// native scrolling
					e.preventDefault();
				}
				if (this.absDistX == undefined || this.absDistX == null) {
					console.log("un de fi ne d");
					e.preventDefault();
				}
				console.log('x = ' + this.absDistX + 'y =' + this.absDistY);
			},
			onTouchEnd : function() {
				// var li_length = $('#main_submenu01 li').length;
				// console.log('li_length = ' + li_length);

				if (0 == main_submenu01_scroll.currPageX) {
					$('.prev').fadeOut(100);
					$('.next').fadeIn(100);
				} else {
					$('.prev').fadeIn(100);
					$('.next').fadeOut(100);
				}
			}
		});

		$('.prev').hide();

		$('.next').click(function() {
			main_submenu01_scroll.scrollToElement('li:last-child', 100);
			$('.prev').fadeIn(100);
			$('.next').fadeOut(100);
		});
		$('.prev').click(function() {
			main_submenu01_scroll.scrollTo(0, 0, 100);
			$('.prev').fadeOut(100);
			$('.next').fadeIn(100);
		});
	}
}

function fncGoHome() {
	window.location.href = "/m/index.do";
}

function fncErrorWrite() {
	if (boardUrl != "") {
		window.location.href = boardUrl;
	} else {
		window.location.href = "/m/board/reportList.do";
	}
}

function fncShowSearch() {
	$.startProcessing();
	// window.scrollTo(0,0);
	$
			.getJSON(
					'/m/search/favKeyword.do',
					function(data) {
						var searchwordList = data.listResult.list;
						if (searchwordList.length > 0) {
							var searchwordHtml = "<div class=\"p_srchArea\" ><div class=\"p_srch\"><div class=\"p_srch_bx\"><input id='totalKeyword' type=\"text\" title=\"검색어입력\" class=\"p_srch_input\"/><input id='btnTotalSearch' type=\"image\" src=\"/m/images/button/btn_hd_srch.gif\" title=\"검색\" class=\"p_srch_btn\"/></div><a href=\"javascript:fncPopupClose()\" class=\"p_srch_cancel\">취소</a></div><div class=\"p_srch_list\" id=\"wrapper\" ><div id=\"scroller\" ><strong>최근검색어</strong><ul>";
							for ( var i = 0; i < searchwordList.length; i++) {
								searchwordHtml += "<li><a href=\'javascript:fncSetSearchWord(\""
										+ searchwordList[i].keyword
										+ "\")\'>"
										+ searchwordList[i].keyword
										+ "</a></li>";
							}
							searchwordHtml += "</ul></div></div></div><div  style='height:50px'></div>";
							$("#nahfWrap").hide();
							$.stopProcessing();
							$(".Layerpop").html(searchwordHtml);
							$(".Layerpop").show();
							popupOpenYN = true;
							fncSearchFormInit();
							new iScroll('wrapper');

						}
					});

	$(".Layerpop").html(searchListHtml);
	$(".Layerpop").show();

}

function fncSetSearchWord(word) {
	$("#totalKeyword").val(word);
}

function fncPopupClose() {
	$("#nahfWrap").show();
	$(".Layerpop").hide();
	popupOpenYN = false;
}

/**
 * appendSearchConditionSet
 * 
 * @param formObject
 *            jQuery object
 * @param type
 *            search target field
 * @param method
 *            EQ | LIKE | GT | GE | LT | LE
 * @param keyword
 *            search keyword
 * @param conjunction
 *            AND | OR | (OR | )OR | (AND | )AND
 */
function appendSearchConditionSet(formObject, type, method, keyword,
		conjunction) {
	var searchKeywordType = $("<input type='hidden' name='searchKeywordType'></input>"); // 검색대상필드
	var searchKeywordMethod = $("<input type='hidden' name='searchKeywordMethod'></input>"); // 검색방법(LIKE,
																								// =,
																								// ...)
	var searchKeyword = $("<input type='hidden' name='searchKeyword'></input>"); // 키워드
	var searchKeywordConjunction = $("<input type='hidden' name='searchKeywordConjunction'></input>"); // 접속사(AND,
																										// OR,
																										// ...)

	searchKeywordType.val(type);
	searchKeywordMethod.val(method);
	searchKeyword.val(keyword);
	searchKeywordConjunction.val(conjunction);

	formObject.append(searchKeywordType);
	formObject.append(searchKeywordMethod);
	formObject.append(searchKeyword);
	formObject.append(searchKeywordConjunction);
}

/**
 * removeSpecialChar 통합검색과 상세검색에서 입력되는 검색키워드에 적용 특수문자를 공백으로 대치하여 반환
 * 
 * @param keyword
 */
function removeSpecialChar(keyword) {
	var specialChar = /[~!\#$^*\=+:;?"<,.>'()\/]/g;
	var retKeyword = keyword;
	if (specialChar.test(keyword)) {
		retKeyword = keyword.replace(specialChar, " ");
		alert("검색에서 사용할 수 없는 문자가 포함되어있습니다.\r\n키워드:'" + keyword + "'(은)는 '"
				+ retKeyword + "'(으)로 대치됩니다.");
	}
	return retKeyword;
}

// 통합검색수행(인기검색어 함께 이용 )
function searchResult(inputKeyword) {
	var keyword = removeSpecialChar(inputKeyword);
	if ($.trim(keyword)) {
		$("#totalSearchForm #totalSearchWord").val(keyword);
		$('#totalSearchForm').submit();
	} else {
		alert('입력된 검색어가 올바르지 않습니다. 다시입력해주세요');
	}
}

function fncSearchFormInit() {
	/***************************************************************************
	 * 통합검색관련
	 **************************************************************************/
	// 통합검색 키워드입력란 엔터 처리
	$("#totalKeyword").keyup(function(e) {
		if (e.keyCode == 13) {
			if ($.trim($(this).val())) {
				searchResult($.trim($(this).val()));
			} else {
				alert('검색어를 입력하세요');
			}
		}
	});
	// 통합검색 버튼 클릭처리
	$(".searchBtn").click(function(e) {
		if ($.trim($("#totalKeyword").val())) {
			searchResult($.trim($("#totalKeyword").val()));
		} else {
			alert('검색어를 입력하세요');
		}
	});
	
	// 통합검색 버튼 클릭처리
	$(".btn_detail_sch").click(function(e) {
		window.location.href = "/search/detailSearch.do";
	});
}

function goDir(url) {
	$.processing();
	window.location.href = url;
}

function fncWinOpen(url) {
	window.open(url);
}

/**
 * 디렉토리 경로 보기/숨기기
 * 
 * @param type
 */
var boolContLocOnOff = true;
function fncContLocOnOff(type) {
	if (boolContLocOnOff) {
		$(".cont_loc").show();
	} else {
		$(".cont_loc").hide();
	}
	boolContLocOnOff = !boolContLocOnOff;
}

function searchResultList() {

};

var oLoading = null;
$.startProcessing = function(time) {
	if (oLoading == null) {
		oLoading = new jindo.m.Loading();
	}
	oLoading.show();
};

$.stopProcessing = function(time) {
	oLoading.hide();
};

$.processing = function() {
	$.processingTimer(5000);
};

$.processingTimer = function(time) {
	$.startProcessing();
	setTimeout($.stopProcessing, time);
};

function fncSearchResultList(itemId, setId) {

	$("#searchListForm input[name='setId']").val(setId);
	$("#searchListForm input[name='itemId']").val(itemId);

	$("#searchListForm input[name='rowPerPage']").val(20);
	$("#searchListForm input[name='page']").val(1);
	$("#searchListForm input[name='sort']").val("mainTitle");
	$("#searchListForm input[name='dir']").val("ASC");
	$('#searchListForm').submit();
}

function readyMessage() {
	alert("서비스 준비중입니다.");
}

function popdetail(itemId) {
	var popUrl = "/item/itemData.do?itemId=" + itemId + "&viewType="
			+ VIEW_DETAIL; // 팝업창에 출력될 페이지 URL
	var popOption = "width=620, height=810, left=0, resizable=no , toolbars = no, top=0, scrollbars=no, status=no;"; // 팝업창
																														// 옵션(optoin)
	window.open(popUrl, "DETAIL_POPUP", popOption);
}

// 전자지도 팝업
function popOpen(areaCd) {
	var popUrl = "/item/map.do"; // 팝업창에 출력될 페이지 URL
	if (areaCd && areaCd.length > 0) {
		popUrl += "?areaCd=" + areaCd;
	}
	var popOption = "width=1024, height=768, left=0, resizable=no , toolbars=no, top=0, scrollbars=yes, status=no;"; //팝업창 옵션(optoin)
	window.open(popUrl,"WRICE_MAP",popOption);
	//window.open(popUrl, "WRICE_MAP");
}

function viewMap(itemId) {
	var popUrl = "/item/itemData.do"; // 팝업창에 출력될 페이지 URL
	popUrl += "?itemId=" + itemId + "&viewType=" + VIEW_MAP;
	var popOption = "width=800, height=700, left=0, resizable=no , toolbars = no, top=0, scrollbars=no, status=no;"; // 팝업창
																														// 옵션(optoin)
	window.open(popUrl, "VIEW_MAP", popOption);
	// window.open(popUrl,"_blank");
}

function searchWithinResults() {
	var keyword = document.getElementById("keyword").value;
	var keywordType = document.getElementById("keywordType").value;
	
	if(keyword == "") {
		alert("검색어를 입력하세요.");
		return;
	}
	
	var searchVO = document.getElementById("searchVO");
	
	searchVO.searchWord.value = keyword;
	searchVO.searchType.value = keywordType;
	searchVO.page.value = 1;
	searchVO.submit();
}
